// Register/index.js
import {
    request
} from '@/utils/request'
import dayjs from 'dayjs'
import {
    customNavigate,
    customRedirect
} from '@/utils/route'
import {
    getParams,
    showToast
} from '@/utils/util'
import {
    fetchUserRegister,
    fetchUserUpdate
} from '@/services/user'
const apiMapping = {
    'insert': fetchUserRegister,
    'edit': fetchUserUpdate
};
Page({

    /**
     * 页面的初始数据
     */
    data: {
        minDate: 0,
        maxDate: 0,
        type: 'insert',
        formState: {
            guardians: [{
                relation: null,
                name: null,
                phone: null,
                is_emergency: null
            }],
            name: null,
            sex: null,
            id_number: null,
            national: null,
            blood_type: null,
            address_province_id: null,
            address_province: null,
            address_city_id: null,
            address_city: null,
            address_area_id: null,
            address_area: null
        },
        sex: [{
            text: '男',
            value: 1
        }, {
            text: '女',
            value: 0
        }],
        blood_type: [{
            text: 'A型',
            value: 'A型'
        }, {
            text: 'B型',
            value: 'B型'
        }, {
            text: 'AB型',
            value: 'AB型'
        }, {
            text: 'O型',
            value: 'O型'
        }],
        national: [{
            text: "汉族",
            value: "汉族"
        }, {
            text: "蒙古族",
            value: "蒙古族"
        }, {
            text: "回族",
            value: "回族"
        }, {
            text: "藏族",
            value: "藏族"
        }, {
            text: "维吾尔族",
            value: "维吾尔族"
        }, {
            text: "苗族",
            value: "苗族"
        }, {
            text: "彝族",
            value: "彝族"
        }, {
            text: "壮族",
            value: "壮族"
        }, {
            text: "布依族",
            value: "布依族"
        }, {
            text: "朝鲜族",
            value: "朝鲜族"
        }],
        options: [],
        showColumns: false
    },
    onShowColumns(e) {
        const {
            column
        } = e.currentTarget.dataset;
        this.setData({
            columns: this.data[column],
            showColumns: true,
            columnType: column
        })
    },
    onColumnConfirm(e) {
        this.setData({
            [`formState.${this.data.columnType}`]: e.detail.value.value,
            columnType: null,
            showColumns: false,
            columns: []
        })
    },
    onColumnCancel() {
        this.setData({
            columnType: null,
            showColumns: false,
            columns: []
        })
    },
    onShowCascader() {
        this.setData({
            showCascader: true
        })
    },
    onAddContact() {
        let {
            formState: {
                guardians
            }
        } = this.data;
        guardians.push({
            relation: null,
            name: null,
            phone: null,
            is_emergency: null
        })
        this.setData({
            'formState.guardians': guardians
        })
    },
    onContactFormChange(e) {
        const {
            item,
            index
        } = e.currentTarget.dataset;
        let {
            formState: {
                guardians
            }
        } = this.data;
        guardians[index][item] = e.detail;
        this.setData({
            'formState.guardians': guardians
        })
    },
    onFieldChange(e) {
        this.setData({
            [`formState.${e.currentTarget.dataset.field}`]: e.detail
        })
    },
    onLoad(options) {
        console.log(options)
        console.log(getParams(options.params))
        const {
            token,
            type
        } = getParams(options.params)
        this.setData({
            token,
            type: type == 'edit' ? type : 'insert'
        }, () => {
            if (type == 'edit') {
                this.searchUserInfo()
            }
        })
        this.searchProvince()
    },
    searchUserInfo() {
        const _this = this;
        request({
            url: '/elderly/query_by_id',
            method: 'POST',
            header: {
                token: wx.getStorageSync('userInfo').token
            }
        }).then(res => {
            let guardians = res.data.guardians.map(t => {
                return {
                    name: t.namedesensitization,
                    phone: t.phonedesensitization,
                    relation: t.relation,
                    is_emergency: t.is_emergency
                }
            })
            this.setData({
                'formState.name': res.data.namedesensitization,
                'formState.sex': res.data.sex,
                'formState.id_number': res.data.id_numberdesensitization,
                'formState.blood_type': res.data.blood_type,
                'formState.national': res.data.national,
                'formState.address_province': res.data.address_province,
                'formState.address_city': res.data.address_city,
                'formState.address_area': res.data.address_area,
                'formState.address_province_id': res.data.address_province_id,
                'formState.address_city_id': res.data.address_city_id,
                'formState.address_area_id': res.data.address_area_id,
                'formState.address': res.data.address,
                'formState.guardians': guardians,
                userInfo: {
                    ...res.data
                }
            })
        })
    },
    searchProvince() {
        const _this = this;
        request({
            url: '/sysProvince/getlist',
            method: 'POST',
            data: {}
        }).then(res => {
            _this.setData({
                options: res.data.map(t => {
                    return {
                        text: t.name,
                        value: t.id
                    }
                })
            })
        })
    },
    searchCity(value, index) {
        const _this = this;
        request({
            url: '/sysCity/query_by_pid',
            method: 'POST',
            data: {
                id: value
            }
        }).then(res => {
            this.setData({
                [`options[${index}].children`]: res.data.map(t => {
                    return {
                        text: t.name,
                        value: t.id
                    }
                })
            })
        })
    },
    searchRegion(value, second, first) {
        const _this = this;
        request({
            url: '/sysArea/query_by_pid',
            method: 'POST',
            data: {
                id: value
            }
        }).then(res => {
            this.setData({
                [`options[${first}].children[${second}].children`]: res.data.map(t => {
                    return {
                        text: t.name,
                        value: t.id
                    }
                })
            })
        })
    },
    onCascaderChange(e) {
        const {
            value,
            tabIndex,
            selectedOptions
        } = e.detail;
        let index;
        this.data.options.map((t, idx) => {
            if (t.value == selectedOptions[0].value) {
                index = idx;
            }
        })
        if (tabIndex == 0) {
            this.searchCity(value, index)
        } else {
            let secIndex;
            selectedOptions[0].children.map((t, idx) => {
                if (t.value == value) {
                    secIndex = idx;
                }
            })
            this.searchRegion(value, secIndex, index)
        }
    },
    onCloseAdd() {
        this.setData({
            showCascader: false
        })
    },
    onFinish(e) {
        const {
            selectedOptions,
            value
        } = e.detail;
        if (selectedOptions.length < 3) return;
        const fieldValue = selectedOptions
            .map((option) => option.value);
        const fieldName = selectedOptions
            .map((option) => option.text || option.name);
        this.setData({
            'formState.address_province_id': fieldValue[0],
            'formState.address_city_id': fieldValue[1],
            'formState.address_area_id': fieldValue[2],
            'formState.address_province': fieldName[0],
            'formState.address_city': fieldName[1],
            'formState.address_area': fieldName[2],
            'formState.address': fieldName.join('/'),
            showCascader: false
        })
    },
    onDelete(e) {
        let {
            guardians
        } = this.data.formState;
        guardians.splice(e.currentTarget.dataset.index, 1)
        this.setData({
            'formState.guardians': guardians
        })
    },
    onTap(e) {
        this.setData({
            index: e.currentTarget.dataset.index,
            actionShow: true
        })
    },
    onSelect(e) {
        this.setData({
            [`formState.guardians[${e.currentTarget.dataset.target}].is_emergency`]: e.detail.name == '是' ? 1 : 0,
            actionShow: false
        })
    },
    onClose(e) {
        this.setData({
            [`formState.guardians[${e.currentTarget.dataset.target}].is_emergency`]: null,
            actionShow: false
        })
    },
    async onRegister() {
        const that = this;
        const validationRules = {
            name: {
                required: true,
                message: '请输入姓名'
            },
            sex: {
                required: true,
                message: '请选择性别'
            },
            birthday: {
                required: that.data.type === 'edit' ? false : true,
                message: '请选择生日'
            },
            blood_type: {
                required: true,
                message: '请选择血型'
            },
            national: {
                required: true,
                message: '请选择民族'
            },
            address: {
                required: true,
                message: '请选择所属区域'
            },
            guardians: [{
                name: {
                    required: true,
                    message: '请输入姓名'
                },
                relation: {
                    required: true,
                    message: '请输入与老人关系'
                },
                phone: {
                    required: true,
                    message: '请输入正确的联系方式',
                    pattern: /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
                },
                is_emergency: {
                    required: true,
                    message: '请选择是否为紧急联系人'
                }
            }]
        };

        const validateForm = () => {
            let isValid = true;
            Object.keys(validationRules).forEach(fieldName => {
                if (fieldName === 'guardians') {
                    that.data.formState.guardians.forEach((guardian, index) => {
                        Object.keys(validationRules.guardians[0]).forEach(guardianField => {
                            const fieldRules = validationRules.guardians[0][guardianField];
                            if (fieldRules.required) {
                                const fieldValue = guardian[guardianField];
                                if (fieldRules.pattern) {
                                    if (!fieldRules.pattern.test(fieldValue)) {
                                        isValid = false;
                                        wx.showToast({
                                            title: fieldRules.message,
                                            icon: 'none'
                                        });
                                    }
                                } else if (fieldValue == null || fieldValue === undefined) {
                                    isValid = false;
                                    wx.showToast({
                                        title: fieldRules.message,
                                        icon: 'none'
                                    });
                                }
                            }
                        });
                    });
                } else {
                    const fieldRules = validationRules[fieldName];
                    if (fieldRules.required) {
                        const fieldValue = that.data.formState[fieldName];
                        if (fieldRules.pattern) {
                            if (!fieldRules.pattern.test(fieldValue)) {
                                isValid = false;
                                wx.showToast({
                                    title: fieldRules.message,
                                    icon: 'none'
                                });
                            }
                        } else if (fieldValue == null || fieldValue === undefined) {
                            isValid = false;
                            wx.showToast({
                                title: fieldRules.message,
                                icon: 'none'
                            });
                        }
                    }
                }
            });
            return isValid;
        };

        if (!validateForm()) {
            return;
        }

        const params = {
            ...this.data.formState
        };

        if (params.birthday) {
            params.birthday = dayjs(params.birthday).format('YYYYMMDD');
        }

        if (that.data.type === 'edit') {
            params.id = that.data.userInfo.id;
            if (that.data.formState.name === that.data.userInfo.namedesensitization) {
                params.name = that.data.userInfo.name;
            }
            if (that.data.formState.id_number === that.data.userInfo.id_numberdesensitization) {
                params.id_number = that.data.userInfo.id_number;
            }
            if (that.data.formState.address === that.data.userInfo.addressdesensitization) {
                params.address = `${that.data.userInfo.address_province}/${that.data.userInfo.address_city}/${that.data.userInfo.address_area}`;
            }
            params.guardians.map((t, index) => {
                if (!that.data.userInfo.guardians[index]) return;
                that.data.userInfo.guardians.map(k => {
                    if (t.name === k.namedesensitization) {
                        t.name = k.name;
                    }
                    if (t.phone === k.phonedesensitization) {
                        t.phone = k.phone;
                    }
                });
            });
        }
        try {
            const apiFunction = apiMapping[this.data.type];
            const res = await apiFunction(params, { token: this.data.token });
            if (res.return_code == 'SUCCESS') {
                switch (this.data.type) {
                    case 'insert':
                        showToast('注册成功，等待跳转..', () => {
                            setTimeout(() => {
                                wx.clearStorageSync();
                                customRedirect({
                                    url: '/User/pages/Login/index'
                                })
                            }, 1000)
                        });
                        break;
                    case 'edit':
                        showToast('编辑成功，等待跳转..', () => {
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 1
                                })
                            }, 1000)
                        });
                        break;
                    default:
                        break;
                }
            }
        } catch (error) {
            showToast(error);
        }
    },
    onShowCalendar() {
        this.setData({
            maxDate: new Date().getTime(),
            minDate: dayjs(new Date()).subtract(100, 'year').valueOf(),
            currentDate: new Date().getTime()
        }, () => {
            this.setData({
                showBirthday: true
            })
        })
    },
    onCalendarInput(event) {
        this.setData({
            currentDate: event.detail,
        });
    },
    onBirthdayConfirm(e) {
        this.setData({
            showBirthday: false,
            formState: {
                ...this.data.formState,
                birthday: dayjs(this.data.currentDate).format('YYYY-MM-DD')
            }
        })
    },
    onBirthdayCancel() {
        this.setData({
            showBirthday: false,
            formState: {
                ...this.data.formState,
                birthday: null
            }
        })
    }
})